package com.gmono.managers;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Function;

public class Common {
    static public Connection c=null;
    static
    {

        try
        {
            Class.forName("org.postgresql.Driver");
            c= DriverManager.getConnection("jdbc:postgresql://localhost:5432/myblog","postgres","gmono35");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
    static public <T> ArrayList<T> ResultToCollection(ResultSet set, Function<ResultSet,T> transform) throws SQLException {
        ArrayList<T> lst=new ArrayList<>();
        while(set.next())
        {
            T t=transform.apply(set);
            lst.add(t);

        }
        return lst;
    }

    static public PreparedStatement replaceSql(String sql,Object...paramters)
    {
        try {
            PreparedStatement s=c.prepareStatement(sql);
            for(int i=1;i<=paramters.length;++i)
            {
                Object o=paramters[i-1];
                if(o.getClass()==int.class||o.getClass()==Integer.class)
                {
                    s.setInt(i,(int)o);
                }
                else if(o.getClass()==String.class)
                {
                    s.setString(i,(String)o);
                }
                else if(o.getClass()== LocalDateTime.class)
                {
                    Timestamp t=Timestamp.valueOf((LocalDateTime) o);
                    s.setTimestamp(i,t);
                }
            }
            return s;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     *
     * @param sql
     * @param paramters
     * @return
     */
    static public ResultSet Query(String sql,Object...paramters)
    {
        try {
            return replaceSql(sql,paramters).executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }

    }

    static public int Update(String sql,Object...paramters)
    {
        try {
            return replaceSql(sql,paramters).executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

}
